package com.example.dingdong.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.example.dingdong.daomain.RoleEntity;
import com.example.dingdong.daomain.RouterEntity;
import com.example.dingdong.repository.RoleRepository;
import com.example.dingdong.repository.RouterRepository;


/**
 * @ClassName: RoleService
 * @Description: 角色服务类
 * @Author chengwenxing
 * @DateTime 2021-01-09 12:53:18
 */
@Service
public class RoleService {
	
	@Autowired
	private RoleRepository roleRepository;

	@Autowired
	private RouterRepository routerRepository;

	/*
	 * 保存角色实体
	 */
	@Transactional(rollbackFor = Exception.class) // 抛出异常时，数据进行回滚
	public RoleEntity saveRole(RoleEntity role) {
		return roleRepository.save(role);
	}

	/*
	 * 根据ID查找角色实体
	 */
	@Transactional(rollbackFor = Exception.class)
	public RoleEntity getRole(int id, boolean delFlag) {
		return roleRepository.findByIdAndDelFlag(id, delFlag);
	}

	/*
	 * 根据名称查找角色实体
	 */
	@Transactional(rollbackFor = Exception.class)
	public RoleEntity getRoleByName(String roleName, boolean delFlag) {
		return roleRepository.findByRoleNameAndDelFlag(roleName, delFlag);
	}

	/*
	 * 查找所有角色
	 */
	@Transactional(rollbackFor = Exception.class)
	public List<RoleEntity> getRole() {
		return roleRepository.findByDelFlag(true);
	}

	/*
	 * 删除角色
	 */
	@Transactional(rollbackFor = Exception.class)
	public void delRole(RoleEntity role) {
		role.setDelFlag(false);
		saveRole(role);
	}

	/*
	 * 更新角色
	 */
	@Transactional(rollbackFor = Exception.class)
	public void updateRole(int id, String roleName, String remark) {
		roleRepository.updateRole(id, roleName, remark);
	}

	/*
	 * 角色和路由绑定
	 */
	@Transactional(rollbackFor = Exception.class)
	public void bindRouter(RoleEntity role, RouterEntity router) {
		role.getRouterList().add(router);
		this.saveRole(role);

		router.getJoinRoleList().add(role);
		routerRepository.save(router);

	}

	/*
	 * 角色换绑路由数组
	 */
	@Transactional(rollbackFor = Exception.class)
	public void updataBindRouter(RoleEntity role, List<RouterEntity> routerList) {
		// 路由数组与角色进行解绑
		List<RouterEntity> list = role.getRouterList();
		for (int i = 0; i < list.size(); i++) {
			RouterEntity router = list.get(i);
			router.getJoinRoleList().remove(role);
			routerRepository.save(router);
		}

		// 路由数组与角色的绑定
		for (int i = 0; i < routerList.size(); i++) {
			RouterEntity router = routerList.get(i);
			router.getJoinRoleList().add(role);
			routerRepository.save(router);
		}

		// 角色和路由的绑定
		role.setRouterList(routerList);
		roleRepository.save(role);
	}
}


